package com.redis.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redis.test02.MyRedisUtil;
import com.redis.test03.TestMapper;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2019/9/10 18:06
 * 描述:
 */

@Component
public class TestMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private TestMapper testMapper;

    @Override
    public void onMessage(Message message, byte[] bytes) {

        System.out.println("==============入队操作==========");

        byte[] body = message.getBody();
        String json = new String(body);
       try{

           JSONObject jsonObject = JSON.parseObject(json);

           boolean lock = MyRedisUtil.getLock(jsonObject.getString("key"), jsonObject.getString("requestId"), redisTemplate, "50");

           Map<String, Object> byId=null;

           if(lock){
               byId=testMapper.getById(1L);

               Object stock = byId.get("stock");

               byId.put("stock",Integer.valueOf(stock.toString())-1);

               testMapper.updateGoodsStock(byId);

               MyRedisUtil.unLock(jsonObject.getString("key"), jsonObject.getString("requestId"), redisTemplate);
           }else{
               //入队操作
               redisTemplate.convertAndSend("TEST",json);
           }

       }catch (Exception e){

           e.printStackTrace();
       }finally {
           json=null;
       }



    }
}
